package com.salesmonitoring.accounts.view;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;

import org.jdesktop.swingx.JXDatePicker;
import org.jdesktop.swingx.calendar.JXMonthView;

import com.salesmonitoring.accounts.controller.AdminController;
import com.salesmonitoring.accounts.controller.MarketingAssistantController;
import com.salesmonitoring.accounts.model.User;
import com.salesmonitoring.accounts.view.AdminUI.RowListener;
import com.salesmonitoring.controller.Exporter;
import com.salesmonitoring.model.RepairShop;
import com.salesmonitoring.model.Transaction;
import com.salesmonitoring.view.LoginScreen;

@SuppressWarnings("serial")
public class MarketingAssistantUI extends JFrame implements ActionListener {

	private JPanel marketingAssistantPanel, usersTabPanel, reportsTabPanel,
			monitoringTabPanel;

	private JTabbedPane tabPanel;
	
	private JButton logoutButton, addButton, viewAllButton,
			editUserButton, acctSettingButton, searchButton, addReportButton, editReportButton, deleteReportButton, exportButton;

	private JLabel lblSMS, lblFirstnameRole, lblOldCustName, lblNewCustName,
			lblDateRequested, lblDateOfRepo, lblDateSold, lblAccountOfficer,
			lblPlateNumber, lblClass, lblWarehouse, lblModel, lblEngine,
			lblChassis, lblRepairShop, lblRepairShopOwner,
			lblRepairShopAddress, lblRepairShopWarehouse, lblMonth, lblYear;

	private JTextField oldCustNameTextField, newCustNameTextField,
			motorChassisTextField, motorEngineTextField, motorModelTextField,
			motorPlateNumberTextField, motorClassTextField,
			repairShopOwnerTextField, repairShopAddressTextField,
			repairShopWarehouseTextField;

	private JComboBox accountOfficerComboBox,
			motorWarehouseComboBox, repairShopComboBox, monthComboBox, yearComboBox;

	JXDatePicker dateRequestedPicker;

	private JXDatePicker dateRepoPicker, dateSoldPicker;
	
	private JTable accountsTable, reportsTable;
	private JScrollPane accountsTableScrollPanel, reportsTableScrollPanel;
	
	private EditUserUI editUserPopup;
	private AccountSettingsUI acctSettingsPopup;
	private RepairShop shop;
	
	public int columnsNumber = 4;
	public int accountsNumber = 5;
	public int reportsNumber = 2;
	public int reportsColumnsNumber = 16;
	public String username, name, role, warehouse, originalCustName;
	private ArrayList<User> users;
	private ArrayList<Transaction> reports;
	private HashMap<String, Object> details;

	private int curentYear = Calendar.getInstance().get(Calendar.YEAR);
	private int stringInt[] = {curentYear+1,curentYear+2,curentYear+3,curentYear+4,curentYear+5};
	private String[] monthStrings = { "", "Jan", "Feb", "Mar", "Apr", "May","Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
//	private String[] yearlist ={"2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", };
	private String[] yearlist ={ "", "2013", "2012", "2011", "2010", "2009", "2009", "2007", "2006", "2005", "2014", "2003", "2002", "2001", };
	private String[] names, shops, reportsTableTitles;
	private boolean aoFlag = false, oldCustomerFlag = false, newCustomerFlag = false, rsFlag = false,
			modelFlag = false, engineFlag = false, chassisFlag = false, plateFlag = false, classFlag = false, warehouseFlag  = false;

	private AddReportUI addReportPopup;

	private EditReportUI editReportPopup;

	
	public MarketingAssistantUI() {

		AdminController adminController = AdminController.getInstance();
	
		this.users = adminController.getAllUsers();
		this.names = adminController.getAllAONames();
		this.shops = adminController.getAllRepairShops();
		
		initFirstComponents();
	}

	private void initFirstComponents() {

		setTitle("Bank of Makati | Sales Monitoring System");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 1125, 625);

		marketingAssistantPanel = new JPanel();
		marketingAssistantPanel.setLayout(null);
		setContentPane(marketingAssistantPanel);

		lblSMS = new JLabel("Bank of Makati");
		lblSMS.setFont(new Font("Lucida Grande", Font.PLAIN, 22));
		lblSMS.setBounds(10, 8, 260, 29);
		marketingAssistantPanel.add(lblSMS);

//		acctSettingButton = new JButton("Account Settings");
//		acctSettingButton.addActionListener(this);
//		acctSettingButton.setBounds(888, 36, 139, 29);
//		marketingAssistantPanel.add(acctSettingButton);

		lblFirstnameRole = new JLabel("Runette (Marketing Assistant)");
		lblFirstnameRole.setHorizontalAlignment(SwingConstants.RIGHT);
		lblFirstnameRole.setFont(new Font("Lucida Grande", Font.PLAIN, 14));
		lblFirstnameRole.setBounds(740, 12, 360, 26);
		marketingAssistantPanel.add(lblFirstnameRole);

		logoutButton = new JButton("Logout");
		logoutButton.addActionListener(this);
		logoutButton.setBounds(1010, 35, 88, 29);
		marketingAssistantPanel.add(logoutButton);;

		tabPanel = new JTabbedPane(JTabbedPane.TOP);
		tabPanel.setBounds(0, 65, 1109, 532);
		marketingAssistantPanel.add(tabPanel);
		
		editUserPopup = new EditUserUI();
		acctSettingsPopup = new AccountSettingsUI();
		addReportPopup = new AddReportUI();
		editReportPopup = new EditReportUI();

		initUsersTab();
		tabPanel.addTab("User Accounts", null, usersTabPanel, null);
		
		//----ACCOUNTS LIST TABLE
		initTableScrollPanel();
		
		initReportsTab();
		tabPanel.addTab("Reports", null, reportsTabPanel, null);
		
		//initMonitoringTab();
		//tabPanel.addTab("Monitoring", null, monitoringTabPanel, null);
	}

	public void initUsersTab() {

		usersTabPanel = new JPanel();
		usersTabPanel.setLayout(null);

		editUserButton = new JButton("Edit");
		editUserButton.setBounds(1013, 6, 84, 29);
		editUserButton.addActionListener(this);
		usersTabPanel.add(editUserButton);
	}
	
	///----ACCOUNTS
	public void initTableScrollPanel() {
		
		MyTableModel tableModel = new MyTableModel(users.size());
		accountsTable = new JTable(tableModel);
		accountsTable.setBounds(6, 60, 637, 231);
		accountsTable.setFillsViewportHeight(true);
		accountsTable.setShowGrid(true);
		accountsTable.setShowHorizontalLines(true);
		accountsTable.setShowVerticalLines(true);
		accountsTable.getTableHeader().setReorderingAllowed(false);
		
		ListSelectionModel selectionModel = accountsTable.getSelectionModel();  
		selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  
		selectionModel.addListSelectionListener(new RowListener(this, editUserButton)); 
		
		for(int row = 0; row < users.size(); row++) {
			accountsTable.setValueAt(users.get(row).getId(), row, 0);
			accountsTable.setValueAt(users.get(row).getName(), row, 1);
			accountsTable.setValueAt(users.get(row).getWarehouse(), row, 2);
			accountsTable.setValueAt(users.get(row).getRole(), row, 3);
		}

		accountsTableScrollPanel = new JScrollPane(accountsTable);
		accountsTableScrollPanel.setBounds(6, 38, 1093, 442);
		usersTabPanel.add(accountsTableScrollPanel);
	}

	public void initReportsTab() {

		reportsTabPanel = new JPanel();
		reportsTabPanel.setLayout(null);
		
		// ---Account officer 

		lblAccountOfficer = new JLabel("Account Officer");
		lblAccountOfficer.setBounds(10, 13, 109, 16);
		reportsTabPanel.add(lblAccountOfficer);
		
		accountOfficerComboBox = new JComboBox(names);
		accountOfficerComboBox.setBounds(109, 9, 157, 27);
		reportsTabPanel.add(accountOfficerComboBox);
		
		// ---Month

		lblMonth = new JLabel("Month");
		lblMonth.setBounds(278, 13, 41, 16);
		reportsTabPanel.add(lblMonth);
		
		monthComboBox = new JComboBox(monthStrings);
		monthComboBox.setBounds(317, 9, 93, 27);
		reportsTabPanel.add(monthComboBox);
		
		// ---Year

		lblYear = new JLabel("Year");
		lblYear.setBounds(422, 13, 70, 16);
		reportsTabPanel.add(lblYear);
		
		yearComboBox = new JComboBox(yearlist);
		yearComboBox.setBounds(451, 9, 93, 27);
		reportsTabPanel.add(yearComboBox);
		
		//--
		searchButton = new JButton("Search");
		searchButton.setBounds(550, 9, 81, 27);
		searchButton.addActionListener(this);
		reportsTabPanel.add(searchButton);

		exportButton = new JButton("Export to PDF");
		exportButton.setBounds(850, 9, 119, 27);
		exportButton.setEnabled(false);
		exportButton.addActionListener(this);
		reportsTabPanel.add(exportButton);
		
		addReportButton = new JButton("Add Report");
//		addReportButton.setBounds(737, 9, 119, 27);
		addReportButton.setBounds(978, 9, 119, 27);
		addReportButton.addActionListener(this);
		reportsTabPanel.add(addReportButton);

//		editReportButton = new JButton("Edit Report");
//		editReportButton.setBounds(850, 9, 119, 27);
//		editReportButton.addActionListener(this);
//		reportsTabPanel.add(editReportButton);
//
//		deleteReportButton = new JButton("Delete Report");
//		deleteReportButton.setBounds(963, 9, 119, 27);
//		deleteReportButton.addActionListener(this);
//		reportsTabPanel.add(deleteReportButton);
	}
	
	public void initReportsTable() {
		
		ReportTableModel reportTableModel = new ReportTableModel(reports.size());
		reportsTableTitles = reportTableModel.getTitles();
		reportsTable = new JTable(reportTableModel);
		reportsTable.setFillsViewportHeight(true);
		reportsTable.setShowGrid(true);
		reportsTable.setShowHorizontalLines(true);
		reportsTable.setShowVerticalLines(true);
		reportsTable.getTableHeader().setReorderingAllowed(false);
		
		ListSelectionModel selectionModel = reportsTable.getSelectionModel();  
		selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  
		selectionModel.addListSelectionListener(new ReportRowListener(this, addReportButton, editReportButton, deleteReportButton)); 
		
		if(reports.isEmpty()) {
			exportButton.setEnabled(false);
		} else {
			exportButton.setEnabled(true);
		}
		
		for(int row = 0; row < reports.size(); row++) {
									
			reportsTable.setValueAt(reports.get(row).getDateRequested(), row, 0); //Date Requested - Date
			reportsTable.setValueAt(reports.get(row).getOldCustomer(), row, 1); //Original Customer - String
			reportsTable.setValueAt(reports.get(row).getAccountNumber(), row, 2); //Account # - int
			reportsTable.setValueAt(reports.get(row).getNewCustomer(), row, 3); //New Buyer - String
			reportsTable.setValueAt(reports.get(row).getMotorWarehouse(), row, 4); //Warehouse - String
			reportsTable.setValueAt(reports.get(row).getDateSold(), row, 5);//Date Sold - Date
			reportsTable.setValueAt(reports.get(row).getMotorModel(), row, 6); 	//Model - String
			reportsTable.setValueAt(reports.get(row).getMotorEngine(), row, 7); //Engine - int
			reportsTable.setValueAt(reports.get(row).getMotorChassis(), row, 8); //Chassis - int
			reportsTable.setValueAt(reports.get(row).getDateRepo(), row, 9);//Date Repo - Date
			reportsTable.setValueAt(reports.get(row).getMotorPlate(), row, 10);//Plate # - String
			reportsTable.setValueAt(reports.get(row).getAsmf(), row, 11);	//ASMF # - int
			reportsTable.setValueAt(reports.get(row).getMotorClass(), row, 12);//Class - String
			reportsTable.setValueAt(reports.get(row).getRs(), row, 13);// RS Code - String
		}
		
		//This Scroll Panel holds the Table - But table is displayed on click of "Search"
		reportsTableScrollPanel = new JScrollPane(reportsTable);
		reportsTableScrollPanel.setBounds(10, 42, 1087, 438);
		reportsTabPanel.add(reportsTableScrollPanel);
	}
	

	@Override
	public void actionPerformed(ActionEvent e) {

		if (e.getActionCommand().equals("Register")) {

		} else if (e.getActionCommand().equals("Edit")) {
			if(!checkForActiveWindows()){ 
				editUserPopup.setDetails(username, name, warehouse, role);
				editUserPopup.setLocationRelativeTo(null);
				editUserPopup.setVisible(true);
			}
			
		} else if(e.getActionCommand().equals("Account Settings")) {
			
			if(!checkForActiveWindows()) {
				acctSettingsPopup.setLocationRelativeTo(null);
				acctSettingsPopup.setVisible(true);
			}
			
		} else if (e.getActionCommand().equals("Add Report")) {
			
			if(!checkForActiveWindows()) {
				addReportPopup.setLocationRelativeTo(null);
				addReportPopup.setVisible(true);
			}
			
		} else if (e.getActionCommand().equals("Edit Report")) {
			
			if(!checkForActiveWindows()) {
				editReportPopup.setLocationRelativeTo(null);
				editReportPopup.setVisible(true);
			}

		} else if (e.getActionCommand().equals("Export to PDF")) {
			
			Exporter exporter = new Exporter(reports, reportsTableTitles);
			exporter.setReportTitle(accountOfficerComboBox.getSelectedItem().toString(),
					monthComboBox.getSelectedItem().toString(), yearComboBox.getSelectedItem().toString());
			exporter.export();
			
		} else if(e.getActionCommand().equals("Search")) {
			
			String officer = accountOfficerComboBox.getSelectedItem().toString();
			String month = monthComboBox.getSelectedItem().toString();
			String year = yearComboBox.getSelectedItem().toString();
			
			MarketingAssistantController marketingAssistantController = MarketingAssistantController.getInstance();
			
			reports = marketingAssistantController.getReports(officer, month, year);
			
			initReportsTable();
			
		} else if(e.getActionCommand().equals("Add")) {
			
			
		} else {
			super.dispose();
			LoginScreen loginScreen = new LoginScreen();
			loginScreen.setVisible(true);
			loginScreen.setLocationRelativeTo(null);
		}

	}
	
	public boolean checkForActiveWindows() {
		
		boolean activeWindows = false;
		
		if(this.acctSettingsPopup.isVisible() || this.editUserPopup.isVisible() ||
		   this.addReportPopup.isVisible() || this.editReportPopup.isVisible()) {
			activeWindows = true;
		} else {
			activeWindows = false;
		}
		
		return activeWindows;
	}
	
	public void setCurrentUserName(String name) {
		lblFirstnameRole.setText(name);
	}
	
	class RowListener implements ListSelectionListener  {  
		
	    MarketingAssistantUI readRow;
	    JTable table;
	    JButton edit, delete;
	   
	    public RowListener(MarketingAssistantUI rar, JButton edit) {  
	        readRow = rar;  
	        table = readRow.accountsTable;
	        this.edit = edit;
	    }  
	   
	    @Override
	    public void valueChanged(ListSelectionEvent e) {  
	        if(!e.getValueIsAdjusting()) {  
	            ListSelectionModel model = table.getSelectionModel();  
	            int lead = model.getLeadSelectionIndex();  
	            getSelectedRowUsername(lead);
	            edit.setEnabled(true);
	        }  
	    }  
	   
	    private void getSelectedRowUsername(int rowIndex)  {
	    	
	    	username = (String) table.getValueAt(rowIndex, 0);
	        name = (String) table.getValueAt(rowIndex, 1);
	        warehouse = (String) table.getValueAt(rowIndex, 2);
	        role = (String) table.getValueAt(rowIndex, 3);

	    }
	} 
	
	class ReportRowListener implements ListSelectionListener  {  
		
	    MarketingAssistantUI readRow;
	    JTable table;
	    JButton addReport, editReport, deleteReport;
	   
	    public ReportRowListener(MarketingAssistantUI rar, JButton addReport, JButton editReport, JButton deleteReport) {  
	        readRow = rar;  
	        table = readRow.reportsTable;
	        this.addReport = addReport;
	        this.editReport = editReport;
	        this.deleteReport = deleteReport;
	    }  
	   
	    @Override
	    public void valueChanged(ListSelectionEvent e) {  
	        if(!e.getValueIsAdjusting()) {  
	            ListSelectionModel model = table.getSelectionModel();  
	            int lead = model.getLeadSelectionIndex();  
	            getSelectedRowDateRequested(lead);
	        }  
	    }  
	   
	    private void getSelectedRowDateRequested(int rowIndex)  {
	    	
	        Object o = table.getValueAt(rowIndex, 1);
	        originalCustName = "" + o.toString();
	    }
	}  
}
